﻿using System;
using System.Collections.Generic;
using Fleck;
using FrameCore.LogSystem;
using MemoryPack;
using Share.Memory;

namespace Server.Module.WebSocket.TCP
{
    public class TcpNetModule : ModuleBase
    {
        public TcpNetModule(EModuleType moduleType) : base(moduleType)
        {

        }
        
        private const string uri = "ws://0.0.0.0:9988";
        
        private readonly List<IWebSocketConnection> connectedClients = new List<IWebSocketConnection>();
        public override void Init()
        {
            base.Init();
        }

        public override void Start()
        {
            base.Start();
            var server = new WebSocketServer(uri);
            
            server.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    Console.WriteLine("Client connected.");
                    lock (connectedClients)
                    {
                        connectedClients.Add(socket);
                    }
                };

                socket.OnClose = () =>
                {
                    Console.WriteLine("Client disconnected.");
                    lock (connectedClients)
                    {
                        connectedClients.Remove(socket);
                    }
                };

                socket.OnMessage = message =>
                {
                    Console.WriteLine("Received message===不处理: " + message);
                };

                socket.OnBinary = data =>
                {
                    // 使用 MemoryPack 反序列化对象
                    var req = MemoryPackSerializer.Deserialize<Req>(data);
                    Log.Info($"主类型{req.HeaderMessage.MainType}===副类型==={req.HeaderMessage.SubType}===messageId{req.HeaderMessage.MessageId}");
                    
                    // 将消息返回给发送消息的客户端
                    //socket.Send("Echo: " + req.Message);
                };
            });
        }

        public override void EarlyUpdate()
        {
            base.EarlyUpdate();
        }

        public override void Update()
        {
            base.Update();
        }

        public override void LateUpdate()
        {
            base.LateUpdate();
        }

        public override void End()
        {
            base.End();
        }

        public override void Release()
        {
            base.Release();
        }
    }   
}